from django.shortcuts import get_object_or_404, redirect, render
from django.contrib import auth
from django.urls import reverse, reverse_lazy
from .forms import UserLoginForm, ChangeProfileForm, UserRegisterForm, PasswordChangeForm, SendMessageForm
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import CreateView, TemplateView, DeleteView, UpdateView
from users.models import User, ArchiveUsers
from tasks.models import Comment
from datetime import datetime
from django.core.mail import send_mail
from django.shortcuts import redirect
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from tasks.services import create_password, validate_email


def index(request):
    return render(request, 'layout/index.html', {'actual_year': str(datetime.now().year)})


def about(request):
    if request.method == 'POST':
        form = SendMessageForm(data=request.POST)
        if form.is_valid():
            author = request.POST['author']
            body = request.POST['body']
            comment = Comment.objects.create(author=author, body=body)
            comment.save()

            # send_mail(
            #         f'Сообщение от {author}',
            #         f'Сообщение от {author}:\n{body}',
            #         'revani.web@gmail.com', ['v.rebechenkov@yandex.ru',], fail_silently=False
            #         )
            return render(request, 'layout/index.html')
        else:
            form.add_error('send_msg', 'Вы должны авторизоваться')
            return render(request, 'layout/about.html', {'form': form})
    else:
        form =  SendMessageForm()

    return render(request, 'layout/about.html', {'form': form})


def login(request):
    if request.method == 'POST':
        
        form = UserLoginForm(data=request.POST)
        if form.is_valid():
            email = request.POST['username']
            password = request.POST['password']
            if user := auth.authenticate(email=email, password=password):
                auth.login(request, user)

        else:
            form.add_error('username', 'Неправильный логин или пароль')
            return render(request, 'users/login.html', {'form': form})

        return HttpResponseRedirect(reverse('task:main'))
    else:
        form = UserLoginForm()

    context = {
        'form': form
    }
    return render(request, 'users/login.html', context)


@login_required
def logout(request, name):
    print(name)
    auth.logout(request)
    return redirect('/')


class ChangeUserInfoView(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
    """ Class for change user information
    """
    model = User
    template_name = 'users/profile_change.html'
    form_class = ChangeProfileForm
    success_url = reverse_lazy('task:main')

    def setup(self, request, *args, **kwargs):
        self.user_id = request.user.pk
        return super().setup(request, *args, **kwargs)

    def get_object(self, queryset=None):
        if not queryset:
            queryset = self.get_queryset()
        return get_object_or_404(queryset, pk=self.user_id)
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['user_id'] = self.user_id
        return context


class UserRegisterView(CreateView):
    """ New user registration
    """
    model = User
    template_name = 'users/registration.html'
    form_class = UserRegisterForm
    success_url = reverse_lazy('account:register-done')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['username'] = 'username'
        return context
    
    def form_valid(self, form):
        user = form.save(commit=False)
        email = form['email'].value()
        confirm, username = validate_email(email)
        if confirm:
            user.username = username
            user.display_name = username
            user.email = email
            user.is_active = True
            raw_password, hashed_password = create_password()
            user.password = hashed_password

            user.save()

            archive_user = ArchiveUsers.objects.create(email=email)
            archive_user.save()

            # send_mail(
            #     'Подтверждение регистрации',
            #     f'Спасибо за регистрацию!\nЛогин: {email}\nПароль: {raw_password}',
            #     'revani.web@gmail.com', [email,], fail_silently=False
            #     )
            return HttpResponseRedirect(reverse('account:register-done'))

        return redirect('/')


def registerDone(request):
    return render(request, "users/registration-done.html")


def ChangePassword(request):
    """ Сheck the user in the database and send the new password to the existing user """
    if request.method == 'POST':
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            email = form['email'].value()
            if user := User.objects.get(email=email):
                raw_password, hashed_password = create_password()
                user.password = hashed_password

                user.save()

                send_mail(
                    'Смена пароля',
                    f'Вы воспользовались сменой пароля!\nЛогин: {email}\nПароль: {raw_password}',
                    'revani.web@gmail.com', [email,], fail_silently=False
                    )

        return HttpResponseRedirect(reverse('account:login'))
    else:
        form = PasswordChangeForm()
        context = {
            'form': form,
        }
        template_name = 'users/password-change.html'

        return render(request, template_name, context)
    

class UserDeleteView(DeleteView):
    """ Delete user """
    model = User
    success_url = reverse_lazy('account:delete-user_confirm')
    
    template_name = 'users/delete-user.html'


@receiver(pre_delete, sender=User)
def delete_action(sender, instance, **kwargs):

    username = str(instance).split(' ')[0]
    user = User.objects.get(username=username)
    email = user.email
    queryset = ArchiveUsers.objects.filter(email=email).order_by('date_join')
    archive_user = queryset[0]
    archive_user.date_leave = datetime.now().strftime("%Y-%m-%d")
    archive_user.save()


def deleteConfirm(request):
    return render(request, 'users/delete-user_confirm.html')
